<template>
  <div class="firmware-manage-page pd16" v-loading="pageLoading">
    <el-card class="box-card">
      <div class="search-block">
        <el-form ref="searchParamsRef" :model="searchParams" @submit.prevent="search">
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="产品：" prop="product">
                <el-select v-model="searchParams.product" clearable placeholder="请选择产品" style="width: 100%;">
                  <el-option
                    v-for="item in productOptions"
                    :key="item.productId"
                    :label="item.name"
                    :value="item.productId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
                <el-button @click="reset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="btn-group">
        <el-button type="primary" @click="addFirmware">新增固件版本</el-button>
      </div>

      <div ref="tableBlockRef" class="data-block mt16 table-block">
        <el-table :data="tableData" :max-height="tableHeight" class="nr-table">
          <el-table-column label="产品" prop="productName"></el-table-column>
          <el-table-column label="固件版本名称" prop="firmwareName"></el-table-column>
          <el-table-column label="固件大小" prop="size"></el-table-column>
          <el-table-column label="上传时间" prop="uploadTime">
            <template #default="scope">
              <span>{{scope.row.uploadTime ? moment(scope.row.uploadTime).format('YYYY-MM-DD HH:mm:ss') : ''}}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" prop="updateTime">
            <template #default="scope">
              <span>{{scope.row.updateTime ? moment(scope.row.updateTime).format('YYYY-MM-DD HH:mm:ss') : ''}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-link class="table-btn" type="primary" :underline="false" @click="handleEdit(scope.row)">编辑</el-link>
              <el-link class="table-btn" type="danger" :underline="false" @click="handleDelete(scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <firmware-modify-form
      :dialogVisible="modifyFormVis"
      :formStatus="modifyFormStatus"
      :formData="firmwareFormData.data"
      @update:dialogVisible="(value: boolean) => modifyFormVis = value"
      @submit="getFirmwareData">
    </firmware-modify-form>
  </div>
</template>

<script setup lang="ts" name="FirmwareManage">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import FirmwareModifyForm from './firmware-modify-form.vue'
import { productList } from '@/api/product-manage'
import { firmwareList, firmwareDelete } from '@/api/firmware-manage'
import moment from 'moment'

const pageLoading = ref(false)
const searchParamsRef = ref<FormInstance>()
const searchParams = reactive({
  product: ''
})
const productOptions = ref<any>([])
const tableData = ref<any>([])
const tableBlockRef = ref<any>(null)
const tableHeight = ref(200)
const modifyFormVis = ref(false)
const modifyFormStatus = ref(0)
const firmwareFormData = ref({
  data: {}
})

onMounted(() => {
  resizeTable()
  window.addEventListener('resize', resizeTable, false)
  getProductList()
  getFirmwareData()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeTable, false)
})

// 窗口改变table高度
const resizeTable = () => {
  tableHeight.value = tableBlockRef.value.offsetHeight
}

// 查询
const search = () => {
  getFirmwareData()
}

// 重置
const reset = () => {
  searchParamsRef.value?.resetFields()
}

// 新增
const addFirmware = () => {
  modifyFormVis.value = true
  modifyFormStatus.value = 0
}

// 编辑
const handleEdit = (row: any) => {
  modifyFormVis.value = true
  modifyFormStatus.value = 1
  firmwareFormData.value.data = Object.assign({}, row)
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除【${row.firmwareName}】此固件吗？`,
    '系统提示',
    {
      type: 'warning',
    }
  )
  .then(() => {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
    let params = {
      id: row.id
    }
    firmwareDelete(params).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success(`删除成功！`)
        getFirmwareData()
      } else {
        ElMessage.error(`${res.msg}`)
      }
    }).catch(err => {
      console.log(err)
    })
  })
  .catch(() => {})
}

// 获取产品列表数据
const getProductList = async () => {
  pageLoading.value = true
  await productList().then((res: any) => {
    if (res.code === 0) {
      productOptions.value = [...res.list]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}

// 获取固件表格数据
const getFirmwareData = async () => {
  let params = {
    productId: searchParams.product
  }
  pageLoading.value = true
  await firmwareList(params).then((res: any) => {
    if (res.code === 0) {
      tableData.value = [...res.list]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}
</script>

<style lang="stylus" scoped>
@import '../../style/base.styl'

.firmware-manage-page
  height 100%
  .box-card
    height 100%
    &:deep(.el-card__body)
      height 100%
      position relative
      box-sizing border-box
  .table-block
    top 102px
    bottom 16px
</style>
